﻿import serial
import threading
import time
from tkinter import *
import os
import numpy as np
from pykeyboard import *
from pymouse import *


myMouse = PyMouse()
keyboard = PyKeyboard()

# 界面相关
window_width = 200
window_height = 160


top = Tk()
top.wm_title("手势识别系统")
top.geometry(str(window_width) + 'x' + str(window_height))

result_var = StringVar()

l = Label(top, text='识别结果：', bg='green', font=('Arial', 16), width=30, height=2)
l.pack()

lab1 = Label(top, textvariable=result_var,bg='white', fg='red', font=('楷体', 40), width=6, height=2)
result_var.set(' ')
lab1.place(x=20,y=60)

DATA = ""  # 读取的数据
NOEND = True  # 是否读取结束


# 读数据的本体
def read_data(ser):
    global DATA, NOEND

    # 循环接收数据（此为死循环，可用线程实现）
    while NOEND:
        if ser.in_waiting:
            DATA = ser.read(ser.in_waiting).decode("gbk")
            if DATA == "1":
                result_var.set('放大')
                keyboard.press_key(17)  # 按住ctrl键
                keyboard.tap_key(107)  # 点击"+"键
                keyboard.release_key(17)  # 松开ctrl键
                time.sleep(1)
                result_var.set(' ')
            elif DATA == "2":
                result_var.set('平 移')
                keyboard.tap_key(39)
                time.sleep(1)
                result_var.set(' ')
            elif DATA == "3":
                result_var.set('缩 小')
                keyboard.press_key(17)  # 按住ctrl键
                keyboard.tap_key(109)  # 点击"-"键
                keyboard.release_key(17)  # 松开ctrl键
                time.sleep(1)
                result_var.set(' ')
            elif DATA == "4":
                result_var.set('缩 小')
                keyboard.press_key(17)  # 按住ctrl键
                keyboard.tap_key(98)  # 点击","键
                keyboard.release_key(17)  # 松开ctrl键
                time.sleep(1)
                result_var.set(' ')
            else:
                result_var.set(' ')
            print("receive: ", DATA)
            # print("\n")
            if (DATA == "quit"):
                print("oppo seri has closen.\n>>", end="")


# 打开串口
def open_seri(portx, bps, timeout):
    ret = False
    try:
        # 打开串口，并得到串口对象
        ser = serial.Serial(portx, bps, timeout=timeout)

        # 判断是否成功打开
        if (ser.is_open):
            ret = True
            th = threading.Thread(target=read_data, args=(ser,))  # 创建一个子线程去等待读数据
            th.start()
    except Exception as e:
        print("error!", e)

    return ser, ret


# 关闭串口
def close_seri(ser):
    global NOEND
    NOEND = False
    ser.close()


# 写数据
def write_to_seri(ser, text):
    res = ser.write(text.encode("gbk"))  # 写
    return res


# 读数据
def read_from_seri():
    global DATA
    data = DATA
    DATA = ""  # 清空当次读取
    return data

if __name__ == "__main__":

    # ser, ret = open_seri("COM4", 115200, None) # 串口com4、bps为115200，等待时间为永久
    # if ret == True: # 判断串口是否成功打开
    #     count = write_to_seri(ser, "exit")
    #     print("写入总字节数：", count)

    # 打开一个串口
    #port = input("输入串口名：")
    port = "COM4"
    ser, ret = open_seri(port, 115200, None)  # 串口com4、bps为115200，等待时间为永久
    top.mainloop()
    while True:
        text = input()
        write_to_seri(ser, text)
        if text == "quit":
            close_seri(ser)
            print("bye!")
            break

        top.update()
        top.after(10)








